import * as dd from 'dingtalk-jsapi'

export default {
  data() {
    return {

    };
  },
  created(){

  },
  methods: {
    departmentsPicker(){
      let that = this;
      return new Promise(function(resolve, reject){
        dd.biz.contact.departmentsPicker({
          title: "选择部门",            //标题
          corpId: that.dingConfig.corpId,              //企业的corpId
          multiple:true,            //是否多选
          limitTips:"超出限定部门",          //超过限定人数返回提示
          maxDepartments:1,            //最大选择部门数量
          pickedDepartments:[],          //已选部门
          disabledDepartments:[],        //不可选部门
          requiredDepartments:[],        //必选部门（不可取消选中状态）
          appId: that.dingConfig.agentId,              //微应用的Id
          permissionType:"GLOBAL",          //选人权限，目前只有GLOBAL这个参数
          onSuccess: function(result) {
            return resolve(result.departments);
            /**
             {
            userCount:1,                              //选择人数
            departmentsCount:1，//选择的部门数量
            departments:[{"id":,"name":"","number":}]//返回已选部门列表，列表中每个对象包含id（部门id）、name（部门名称）、number（部门人数）
        }
             */
          },
          onFail : function(err) {
            return reject(err);
          }
        });
      })
    },
    complexPicker(limit, disabledUsers=[] ,pickedUsers=[]){
      let that = this;
      return new Promise(function(resolve, reject){
        dd.ready(function() {
          dd.biz.contact.complexPicker({
            title: "选择人员",            //标题
            corpId: that.dingConfig.corpId,              //企业的corpId
            multiple: true,            //是否多选
            limitTips: "人员超出",          //超过限定人数返回提示
            maxUsers: limit,            //最大可选人数
            pickedUsers: pickedUsers,            //已选用户
            pickedDepartments: [],          //已选部门
            disabledUsers: disabledUsers,            //不可选用户
            disabledDepartments: [],        //不可选部门
            requiredUsers: [],            //必选用户（不可取消选中状态）
            requiredDepartments: [],        //必选部门（不可取消选中状态）
            appId: that.dingConfig.agentId,              //微应用的Id
            permissionType: "GLOBAL",          //可添加权限校验，选人权限，目前只有GLOBAL这个参数
            responseUserOnly: true,        //返回人，或者返回人和部门
            startWithDepartmentId: 0,   //仅支持0和-1
            onSuccess: function (result) {
              console.log("success:" + JSON.stringify(result))
              return resolve(result.users);
              /**
               {
            selectedCount:1,                              //选择人数
            users:[{"name":"","avatar":"","userid":""}]，//返回选人的列表，列表中的对象包含name（用户名），avatar（用户头像），emplId（用户工号）三个字段
            departments:[{"id":,"name":"","number":}]//返回已选部门列表，列表中每个对象包含id（部门id）、name（部门名称）、number（部门人数）
             }
               */
            },
            onFail: function (err) {
              console.log("fail:" + JSON.stringify(err))
              if(err.errorCode==7 || err.errorCode==9){
                //API 授权过期
                //that.dingConfig = {}
                that.$message.error("钉钉授权过期，请重新打开应用")
              }
              return reject(err);
            }
          })
        })

      }
      )
    },
    async getDingConfig() {
      let res = await this.$http({
        url: this.$http.adornUrl('/ding/getConfig'),
        method: 'post',
        params: this.$http.adornParams({
          'url':  window.location.href.substring(0,  window.location.href.indexOf('#')>0?window.location.href.indexOf('#'):window.location.href.length)  //"http://wangzhe.vaiwan.com/" //
        })
      });
      let data = res.data;
      if (data && data.code === 0) {
        return new Promise((resolve, reject) => {
          resolve(data.config)
        })
      } else {
        this.$message.error(data.msg)
      }
    },
    dingLogin(corpId, afterLoginAction){
      let that = this;
      dd.ready(function() {
        dd.runtime.permission.requestAuthCode({
          corpId: corpId,
          onSuccess: function(ddData) {
            that.$http({
              url: that.$http.adornUrl('/ding/login'),
              method: 'post',
              params: that.$http.adornParams({
                'code': ddData.code
              })
            }).then(({data}) => {
              console.log(JSON.stringify(data));
              if (data && data.code === 0) {
                that.$cookie.set('token', data.token)
                that.userInfo = data.userInfo
                that.unPermDingIds = data.unPermDingIds
                that.leaders = data.leaders
                if(afterLoginAction){
                  afterLoginAction();
                }
              } else {
                that.$message.error(data.msg)
              }
            })
          },
          onFail : function(err) {
            that.$message.error(JSON.stringify(err))
          }
        });
      });
    },
    ddError(){
      console.log("init dderror");
      let that = this
      dd.error((error) => {
        console.log(`dd error: ${JSON.stringify(error)}`);
        if(error.errorCode==7 || error.errorCode==9){
          that.dingConfig = {}
          that.userInfo = {}
          that.$message.error("钉钉授权过期，请重新打开应用")
        }
      });
    },
    isPC() {
      let userAgentInfo = navigator.userAgent;
      let Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
      let flag = true;
      for (let v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
          flag = false;
          break;
        }
      }
      return flag;
    },
    loadMembers(){
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl('/ding/listDingUser'),
          method: 'post',
          data: this.$http.adornData({})
        }).then(({data}) => {
            if (data && data.code === 0) {
              return resolve(data.list)
            }
          }
        ).catch(error=>{
          console.info(error)
        })
      })
    },
    run_dd_config(){
      let that = this;
      console.log('dingding config:'+ that.dingConfig.corpId)
      dd.config({
        agentId: that.dingConfig.agentId, // 必填，微应用ID
        corpId: that.dingConfig.corpId,//必填，企业ID
        timeStamp: that.dingConfig.timeStamp, // 必填，生成签名的时间戳
        nonceStr: that.dingConfig.nonceStr, // 必填，生成签名的随机串
        signature: that.dingConfig.signature, // 必填，签名
        type:0,   //选填。0表示微应用的jsapi,1表示服务窗的jsapi；不填默认为0。该参数从dingtalk.js的0.8.3版本开始支持
        jsApiList : [
          'runtime.info',
          'biz.contact.departmentsPicker',
          'biz.contact.complexPicker',
          'biz.contact.choose',
          'device.notification.confirm',
          'device.notification.alert',
          'device.notification.prompt',
          'biz.ding.post',
          'biz.util.openLink',
        ]
      });
      this.ddError();
    },
    mobileSelect(title,arr, callback) {
      dd.device.notification.actionSheet({
        title: title, //标题
        cancelButton: '取消', //取消按钮文本
        otherButtons: arr,
        onSuccess : function(result) {
          callback(result)
        },
        onFail : function(err) {}
      })
    },
    mobileInput(placeholder, text, callback) {
      dd.ui.input.plain({
        placeholder: placeholder, //占位符
        text: text, //默认填充文本
        onSuccess: function(data) {
          if(data.text) {
            callback(data)
          }
        }
      })
    },
    mobileSetTitle(title) {
      dd.biz.navigation.setTitle({
        title : title,//控制标题文本，空字符串表示显示默认文本
      });
    },
    mobileShare(url, title, content, image){
      dd.biz.util.share({
        type: 1,
        url: url,
        title: title,
        content: content,
        image: image,
        onSuccess : function(result) {
        },
        onFail : function(err) {}
      })
    },
    mobileMessage(text) {
      dd.device.notification.toast({
        icon: 'success', //icon样式，不同客户端参数不同，请参考参数说明
        text: text, //提示信息
        duration: 1, //显示持续时间，单位秒，默认按系统规范[android只有两种(<=2s >2s)]
        onSuccess : function(result) {
            /*{}*/

        },
        onFail : function(err) {}
      })
    },
    mobileGetDevice(callback) {
      dd.device.base.getPhoneInfo({
        onSuccess : function(data) {
            callback(data)
        },
        onFail : function(err) {}
      });
    },
    mobileConfirm(content,callback,closeFun) {
      dd.device.notification.confirm({
        message: content,
        title: '提示',
        buttonLabels: ['是', '否'],
        onSuccess : function(result) {
          if(result.buttonIndex === 0) {
            callback()
          }
          if(result.buttonIndex === 1) {
            closeFun && closeFun()
          }
        },
        onFail : function(err) {}
      });
    },
    mobileAlert(content, callback) {
      dd.device.notification.alert({
        message: content,
        title: "提示",//可传空
        buttonName: "确定",
        onSuccess : function() {
          callback && callback()
        },
        onFail : function(err) {}
      });
    },
    mobileSetRightMenu(menuArr,callback) {
      dd.biz.navigation.setMenu({
          backgroundColor : "#ADD8E6",
          textColor : "#ADD8E611",
          items : menuArr,
          onSuccess: function(data) {
            callback(data.id)
          },
          onFail: function(err) {}
      });
    },
    mobileHiddenRightMenu() {
      dd.biz.navigation.setRight({
        show: false,
        control: false,
        text: '发送',//控制显示文本，空字符串表示显示默认文本
        onSuccess : function(result) {
        },
        onFail : function(err) {}
      });
    },
    mobileChosen(chosenArr, defalut, callback) {
      dd.biz.util.chosen({
        source: chosenArr,
        selectedKey: defalut, // 默认选中的key
        onSuccess : function(result) {
          callback(result)
        },
        onFail : function(err) {}
      })
    },
    mobildPullToRefresh(callback) {
      dd.ui.pullToRefresh.enable({
        onSuccess: function() {
          dd.ui.pullToRefresh.stop()
          callback()
        },
        onFail: function() {
        }
    })
    },
    mobileStopRefresh(){
      dd.ui.pullToRefresh.disable()
    },
    dingPreviewPic(img) {
      dd.biz.util.previewImage({
        urls: [img],//图片地址列表
        current: img,//当前显示的图片链接
        onSuccess : function(result) {
            
        },
        onFail : function(err) {}
      })
    },
    mobileSelectDate(date, callback) {
      dd.biz.util.datepicker({
        format: 'yyyy-MM-dd',//注意：format只支持android系统规范，即2015-03-31格式为yyyy-MM-dd
        value: date, //默认显示日期
        onSuccess : function(result) {
          callback(result.value)
        },
        onFail : function(err) {}
      })
    }
  },
  computed:{
/*    dingConfig: {
      get () { return JSON.parse(localStorage.getItem('dingConfig')); },
      set (val) { localStorage.setItem('dingConfig', JSON.stringify(val)) }
    },*/
/*    userInfo: {
      get () { let u = JSON.parse(localStorage.getItem('userInfo')); if(u==null){ u={}}; return u;  },
      set (val) { localStorage.setItem('userInfo', JSON.stringify(val));  }
    },*/
    /*    unPermDingIds:{
          get () { return localStorage.getItem('unPermDingIds');  },
          set (val) { localStorage.setItem('unPermDingIds', val);  }
    },*/
    dingConfig: {
      get () { return this.$store.state.user.dingConfig  },
      set (val) { this.$store.commit('user/updateDingConfig', val)  }
    },
    userInfo: {
      get () { return this.$store.state.user.userInfo  },
      set (val) { this.$store.commit('user/updateUserInfo', val)  }
    },
    unPermDingIds:{
      get () { return this.$store.state.user.unPermDingIds  },
      set (val) { this.$store.commit('user/updateUnPermDingIds', val)  }
    },
    leaders:{
      get () { return this.$store.state.user.leaders  },
      set (val) { this.$store.commit('user/updateLeaders', val)  }
    },
    isManager:{
      get(){ return this.userInfo.isBoss || this.userInfo.isLeaderDept || this.userInfo.isAdmin}
    },
    isAdmin:{
      get(){ return this.userInfo.isAdmin}
    },
    isSaleLeader:{
      get(){
        return this.userInfo.position  === '营销中心总监' || this.isAdmin
      }
    },
    isPoTeam:{
      get(){
        return this.userInfo.position === '运营专员'
      }
    },
    isDreamTeam:{
      get(){
        return this.userInfo.departmentIds == '123146325'
      }
    },
    isFulaiTeam:{
      get(){
        return this.userInfo.departmentIds == '126331492'
      }
    },
    isExceedTeam:{
      get(){
        return this.userInfo.departmentIds == '311594465'
      }
    },
    isB2cTeam:{
      get(){
        return this.userInfo.departmentIds == '122952300'
      }
    }
  },
}
